package com.alks.function.service.impl.procurement;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.excelUtils.ExcelPoiUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.enums.CompanyEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.procurement.CommonMaterialDetailDto;
import com.alks.function.data.dto.procurement.NotOrderDetailsDto;
import com.alks.function.data.dto.procurement.PurchaseOrderDto;
import com.alks.function.data.dto.sys.SdUserDto;
import com.alks.function.data.request.procurement.*;
import com.alks.function.data.request.stockdept.pcfactorystockwork.MyOrdUpRequest;
import com.alks.function.mapper.SdCompanyMapper;
import com.alks.function.mapper.SdDepartmentMapper;
import com.alks.function.mapper.SdPositionMapper;
import com.alks.function.mapper.SdUserMapper;
import com.alks.function.mapper.common.BackMapper;
import com.alks.function.mapper.procurement.*;
import com.alks.function.mapper.stockdept.pcfactorystockquery.*;
import com.alks.function.service.procurement.SporadicClearanceService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.alks.entity.data.enums.ResultCodeEnum.IN_IS_EMPTY;


@Service
@Slf4j
@RequiredArgsConstructor
public class SporadicClearanceServiceImpl  implements SporadicClearanceService {

    private final SD_SQ_SdBomMtlMapper bomMtlMapper;
    private final SporadicClearanceMapper sporadicClearanceMapper;
    private final RedisService redisService;
    private final BackMapper backMapper;
    private final SdUserMapper sdUserMapper;
    private final SdDepartmentMapper sdDepartmentMapper;
    private final SD_SQ_MpPurDisMapper disMapper;
    private final SD_SQ_MpPurMtlLotMapper mtlLotMapper;
    private final SD_SQ_MpMtlSumMapper sumMapper;
    private final SD_SQ_MpMtlLotMapper lotMapper;
    private final SummaryOperationMapper summaryOperationMapper;
    private final MaterialClearanceMapper materialClearanceMapper;

    private final PurCompanyMapper purMapper;
    private final SdPositionMapper sdPositionMapper;

    private final PurCompanyMapper2 purMapper2;
    /**
     * 通用材料明细查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getCommonMaterialDetail(CommonMaterialDetailRequest request) {
        //shiqian TODO  :原先数据11411条，但是数据库里面超过了//11413
        String companyId = UserIdThread.get().getCompanyId();
        String loginName = UserIdThread.get().getLoginName();

        //通用材料
        List<CommonMaterialDetailDto> commonMaterialDetailList = bomMtlMapper.getCommonMaterialDetail(companyId,request);
        // 待订购明细已存在的数据
        List<NotOrderDetailsDto> notOrderDetailsList = sporadicClearanceMapper.getNotOrderDetailsList(companyId,loginName);

        if (ObjectUtils.isNotEmpty(notOrderDetailsList)) {
            // 已经存在的 mtlNo 集合
            Set<String> mtlNoSet = notOrderDetailsList.stream()
                    .map(NotOrderDetailsDto::getMtlNo)
                    .collect(Collectors.toSet());

            if (ObjectUtils.isNotEmpty(commonMaterialDetailList)) {
                for (CommonMaterialDetailDto dto : commonMaterialDetailList) {
                    if (mtlNoSet.contains(dto.getMtlNo())) {
                        dto.setFlag("Y");
                    }
                }
            }
        }

        PageInfo list = new PageInfo(commonMaterialDetailList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", commonMaterialDetailList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 选择通用材料：待请购批处理
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getBatchProcess(List<CommonMaterialDetailDto> request) {
        /*判断*/
        if (ObjectUtils.isEmpty(request)){
            throw new ServiceErrorException("请选择数据");
        }

        /*获取基础数据*/
        String userName = UserIdThread.get().getUserName();
        String loginName = UserIdThread.get().getLoginName();
        String companyId = UserIdThread.get().getCompanyId();
        LocalDateTime now = LocalDateTime.now();

        /*填充数据*/
        //查出最大值,遍历批量的值
        Integer max = sporadicClearanceMapper.getMaxNotOrderDetails(companyId,loginName);
        max = Optional.ofNullable(max)
                .orElse(0);
        for (CommonMaterialDetailDto element : request) {
            // 递增 max 变量，并设置元素的 item 属性
            max = max +1;
            element.setItem(max);
        }

//        String time = "yyMM";
//        String key = "SporadicClearanceOperation/getBatchProcess" + companyId;
//        for (CommonMaterialDetailDto dto : request) {
//            String slipNo = redisService.slipNoGenerate("BF", 3, 2);
//            String prefix = generatePrefix(key, "7", time);
//            String item = companyId + prefix;
//            dto.setItem(item);
//        }

        int count = 0;
        try{
         count = sporadicClearanceMapper.pcReqTempAdd(request,userName,loginName,now,companyId);
        }catch (Exception e){
            throw new ServiceErrorException("相同材料重复添加，请刷新页面后再试！");
        }
        if (count > 0){
            return ResponseInfo.ok("通用材料批处理成功！");
        }else{
            throw new ServiceErrorException("批处理失败！");
        }
    }

    /**
     * 待定购明细查询
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getNotOrderDetailsList() {
        String companyId = UserIdThread.get().getCompanyId();
        String loginName = UserIdThread.get().getLoginName();

        List<NotOrderDetailsDto> notOrderDetailsList = sporadicClearanceMapper.getNotOrderDetailsList(companyId,loginName);

        //用pageInfo对查询结果封装
        PageInfo list = new PageInfo(notOrderDetailsList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", notOrderDetailsList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 待定购明细:修改
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo updateNotOrderDetails(List<NotOrderDetailsDto> request) {
        //修改数量和备注
        String companyId = UserIdThread.get().getCompanyId();
        String loginName = UserIdThread.get().getLoginName();

        int result = sporadicClearanceMapper.updateNotOrderDetails(companyId,loginName,request);
        if(result > 0){
            return ResponseInfo.ok();
        }else{
            return ResponseInfo.ok("修改失败");
        }
    }

    /**
     * 待定购明细:删除
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deleteNotOrderDetails(NotOrderDetailsRequest request) {
        /*获取基础数据*/
        String userName = UserIdThread.get().getUserName();
        String loginName = UserIdThread.get().getLoginName();
        String companyId = UserIdThread.get().getCompanyId();

        int count = sporadicClearanceMapper.deleteNotOrderDetails(request,userName,loginName,companyId);

        if (count > 0){
            return ResponseInfo.ok("删除待定购明细成功");
        }else {
            throw new ServiceErrorException("删除待定购明细失败");
        }
    }

    /**
     * 生成订购资料
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo makeOrderDetails(List<NotOrderDetailsRequest> request) {
        /*获取基础数据*/
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String userName = sysUserTokenDTO.getUserName();
        String loginName = sysUserTokenDTO.getLoginName();
        String companyId = sysUserTokenDTO.getCompanyId();
        String deptId = sysUserTokenDTO.getDeptId();

        //只取值年月日
//        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDate now = LocalDate.now();

        /*判空*/
        if (request == null || request.isEmpty()) {
            throw new ServiceErrorException("请选择数据！");
        }
        //再任何操作前会判断数量是否为空，否则报错：数量不能为空！
        if (request.stream().anyMatch(dto -> dto.getQty() == null)) {
            throw new ServiceErrorException("数量不能为空！");
        }

       /*生成请购单号*/
        String key = "SporadicClearanceOperation/makeOrderDetails" + companyId + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMM"));//自增数字里面加上年月
        String time = "yyMMddHH";
        String prefix = redisService.numberGenerate(key, "5", time);
        String reqNo = CompanyEnum.updateId(companyId) + "L" + prefix;

        /*填充数据*/
        //查公司
        SdUserDto user2 = sdUserMapper.getUser2(sysUserTokenDTO.getUserId(), sysUserTokenDTO.getCompanyId());

        for (NotOrderDetailsRequest r : request) {
            //取lotGroup数据
            String lotNo = r.getLotNo();
            int dashIndex = lotNo.indexOf('-');
            String lotGroup = lotNo;
            if (dashIndex != -1) {
                lotGroup = lotNo.substring(0, dashIndex);
            }
            r.setLotGroup(lotGroup);

            r.setReqNo(reqNo);
            r.setDeptNo(deptId);
            r.setDeptName(user2.getDeptName());
            r.setPurType("零星");
        }

        try {
            /*写入数据*/
            //删除:待定购明细      PC_REQ_TEMP
            int count1 = sporadicClearanceMapper.deleteBatchNotOrderDetails(request, userName, loginName, companyId);
            log.info("删除:待定购明细      PC_REQ_TEMP 成功，影响行数：{}", count1);

            //写入:材料暂收表    insert MP_PUR_DIS 代发明细
            int count2 = disMapper.fdPurDisAddBySdClearan(request, userName, now);
            log.info("写入:材料暂收表      MP_PUR_DIS 成功，影响行数：{}", count2);

            //写入:材料汇总表      MP_MTL_SUM
            int count3 = sumMapper.fdPurDisAddBySdClearan(request, userName, now, loginName);
            log.info("写入:材料汇总表      MP_MTL_SUM 成功，影响行数：{}", count3);

            //写入：指令数据       MP_MTL_LOT
            int count4 = lotMapper.fdPurDisAddBySdClearan(request, userName, now);
            log.info("写入：指令数据       MP_MTL_LOT 成功，影响行数：{}", count4);

            if(count1 > 0 && count2 > 0 && count3 > 0 && count4 > 0){
                return ResponseInfo.ok("生成订购资料,请购单号：" + reqNo);
            }else{
                throw new ServiceErrorException("生成订购资料失败");
            }
        }catch (Exception e){
            log.error("生成订购资料过程中发生异常，请检查日志",e);
            throw new ServiceErrorException("生成订购资料过程中发生异常，请检查日志!");
        }
    }

    /**
     * 进入我的订购单：查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getMyPurchaseOrder(PurchaseOrderRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        String name = UserIdThread.get().getUserName();
        request.setSysUser(name);
        request.setCompanyId(companyId);
        request.setPurType("零星");

        List<PurchaseOrderDto> orderList = materialClearanceMapper.getPurchaseOrderList(request);

        PageInfo summaryPageInfo = new PageInfo(orderList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("lotNoList", orderList);
        map.put("total", summaryPageInfo.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 进入购单：指令明细查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getPurchaseOrderLotDetail(PurchaseOrderDto request) {
        String companyId = UserIdThread.get().getCompanyId();
//        String name = UserIdThread.get().getUserName();
        request.setSysUser(request.getSysUser());
        request.setCompanyId(companyId);
        request.setPurType("零星");

        List<MpMtlLot> orderList = materialClearanceMapper.getPurchaseOrderLotDetail(request);

        PageInfo summaryPageInfo = new PageInfo(orderList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("lotNoList", orderList);
        map.put("total", summaryPageInfo.getTotal());

        return ResponseInfo.ok(map);
    }

    /**
     * 进入我的订购单：编辑
     * @param list
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo updatePurchaseOrder(List<PurchaseOrderDto> list) {
        //可编辑的-未下单：预购量，多购量，（订购数量），厂商代码名字，需求交期，采购备注，厂商回复交期
        //可编辑的-已下单：多购量，需求交期
        /*获取基础数据*/
        String companyId = UserIdThread.get().getCompanyId();
        String name = UserIdThread.get().getUserName();
        if(ObjectUtils.isEmpty(list)){
            throw new ServiceErrorException("请选择记录！");
        }
        list.forEach(dto -> {
            dto.setSysUser(name);
            dto.setCompanyId(companyId);
            // 计算 purQty
            float purQty = (dto.getQty() == null ? 0 : dto.getQty()) +
                    (dto.getMinusQty() == null ? 0 : dto.getMinusQty()) +
                    (dto.getOverQty() == null ? 0 : dto.getOverQty());
            dto.setPurQty(purQty);
        });
        int count = disMapper.batchUpdatePurchaseOrder(list);
        if (count > 0) {
            return ResponseInfo.ok("成功更新 " + count + " 条记录！");
        }else{
            throw new ServiceErrorException("更新失败或无记录更新！");
        }
    }

    /**
     * 进入我的订购单：形成订购单
     * @param r
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo makePurchaseOrder(LotNoRequest4 r) {
        // 1.如果是批量形成订购单，要判断厂商是否一样。如果不一致，报错：存在多个厂商
        List<MyOrdUpRequest> request = r.getRequest();  //页面上的数据集合
        //判空
        if(ObjectUtils.isEmpty(request)){
            throw new ServiceErrorException("请选择记录！");
        }
        //已经形成订购单的不能在生成订购单
        boolean b = request.stream().anyMatch(d -> StringUtils.isNotEmpty(d.getPurFlag()) && d.getPurFlag().equals("Y"));
        if (b) {
            throw new ServiceErrorException("存在已形成订购单的记录，请检查！");
        }
        //存在多个厂商
        long countVendorNo = request.stream()
                .map(MyOrdUpRequest::getVendorNo)
                .filter(vendorNo -> vendorNo != null && !vendorNo.isEmpty())// 过滤掉空字符串
                .distinct()
                .count();
        if (r.getVendorNo() == null && countVendorNo > 1) {
            throw new ServiceErrorException("存在多个厂商！");
        }
        // 判断批量厂商记录为空或者单条厂商
        boolean hasEmptyVendorNo = request.stream()
                .anyMatch(d -> d.getVendorNo() == null || d.getVendorNo().isEmpty());        // 检查是否存在空的 vendorNo
        if (r.getVendorNo() == null && hasEmptyVendorNo) {
            throw new ServiceErrorException("有厂商记录为空,请检查！");
        }
        //批量的需求时期为空或者单条的厂商回复交期交期为空
        boolean result = request.stream()
                .map(MyOrdUpRequest::getInDate)
                .anyMatch(Objects::isNull) && r.getRequiredDate() == null;
        if(r.getRequiredDate() == null && result) {
            throw new ServiceErrorException("记录交期为空！");
        }

        //2.订购单号生成
        /*生成订购单*/
        String companyId = UserIdThread.get().getCompanyId();
        String key = "SporadicClearanceOperation/makePurchaseOrder" + companyId + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMM"));
        //String key = "SporadicClearanceOperation/makePurchaseOrder" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMM"));//自增数字里面加上年月;  //采购要求国内国外的订购单前缀都是RV，所有现在不能用公司作为键了
        String time = "yyMMddHH";
        String prefix = generatePrefix(key, "5", time);
        String k = CompanyEnum.updateId(companyId) + "L";
        String purNo =  k + prefix;

        //获取年月日的时间
        LocalDate now = LocalDate.now();

        //3.可以批量需求日期+厂商
        request.forEach(ord -> {
            //厂商
            ord.setVendorNo(r.getVendorNo()!= null ? r.getVendorNo() : ord.getVendorNo() );
            ord.setVendorName(r.getVendorName()!= null ? r.getVendorName() : ord.getVendorName());
            // 厂商回复交期
            ord.setInDate(r.getRequiredDate() != null ? r.getRequiredDate() : ord.getInDate());
            ord.setPurDate(LocalDate.now());
            // 订单号
            ord.setPurNo(purNo);
            //指令改成通用
            ord.setPurLot(ord.getLotDetail());
            ord.setPurDate(now);

            //下单用量：写到MP_PUR_MTL_LOT
            ord.setPurQty(
                    (ord.getQty() != null ? ord.getQty() : 0) +
                            (ord.getOverQty() != null ? ord.getOverQty() : 0) +
                            (ord.getMinusQty() != null ? ord.getMinusQty() : 0)
            );
        });

        try {
            //4.写入数据库
            /*更新订单*/
            //更新：材料暂收表 MP_PUR_DIS
            int count1 = disMapper.creatPurUpdateByLX(request);
            //写入：材料指令订购单 MP_PUR_MTL_LOT
            int count2 = mtlLotMapper.creatPurUpdate1(request);

            if(count1 > 0 && count2 > 0){
                return ResponseInfo.ok("形成订购单成功,订购单号：" + purNo);
            }else{
                throw new ServiceErrorException("形成订购单失败或无记录形成！");
            }
        }catch (Exception e){
            log.error("形成订购单过程中发生异常，请检查日志：",e);
            throw new ServiceErrorException("形成订购单过程中发生异常，请检查日志！");
        }
    }

    /**
     * 进入所有订购单:查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getAllPurchaseOrder(PurchaseOrderRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        request.setPurType("零星");

        List<PurchaseOrderDto> orderList = materialClearanceMapper.getPurchaseOrderList(request);

        PageInfo summaryPageInfo = new PageInfo(orderList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("lotNoList", orderList);
        map.put("total", summaryPageInfo.getTotal());

        return ResponseInfo.ok(map);
    }

    /**
     * 进入所有订购单:导出订购单
     * @param response
     */
    @Override
    public void exportAllPurchaseOrder(String purNo, HttpServletResponse response) {
        /*模板上填充的公共数据*/
        HashMap<String, Object> map = new HashMap<>();
        //文件名构建
        String fileName = "零星订购单" +DateUtils.dateTimeNow() + ".xlsx";

        /*查询*/
        //查询所有订购单数据
        PurchaseOrderRequest request = new PurchaseOrderRequest();
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String companyId = sysUserTokenDTO.getCompanyId();
        request.setCompanyId(companyId);
        request.setPurType("零星");
        request.setPurNo(purNo);
        List<PurchaseOrderDto> list = materialClearanceMapper.getPurchaseOrderList(request);

        if(ObjectUtils.isNotEmpty(list) && list.size() > 0){
            //模板上其他数据
            PurchaseOrderDto dto = list.get(0);
            //公司
            PurCompany2 companyDto = purMapper2.findPurCompanyInfo(companyId,"面材");
            // 厂商信息
            SdVendor vendorDto = backMapper.getVendorNameByNo(dto.getVendorNo(), companyId);
            String vendorName = dto.getVendorName() != null ? dto.getVendorName() : "";
            // 文件名构建
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyMMdd");
            String date = dto.getPurDate() != null ? sdf1.format( dto.getPurDate()) : "";
            fileName = vendorName + date + "_" + "零星订购单" +DateUtils.dateTimeNow() + ".xlsx";
            //时间转换
            DateTimeFormatter sdf2 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            String sysDate = LocalDateTime.now().format(sdf2);
            SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy/MM/dd");
            SimpleDateFormat sdf4 = new SimpleDateFormat("MM/dd");
            String purDate = dto.getPurDate() != null ?sdf3.format(dto.getPurDate()) : "";

            Float count = 0.0f;
            for (PurchaseOrderDto t : list) {
                String inDateString = dto.getInDate() != null ? sdf4.format(dto.getInDate()) : "";
                t.setInDateString(inDateString);
                t.setMtlColorAndName(t.getMtlColor() + "/" + t.getMtlName());
                if (!ObjectUtils.isEmpty(t.getPurQty())) {
                    count = count + t.getPurQty();
                }
            }
            //填充模板数据
            map.put("mapList", list);
            map.put("p", dto);
            map.put("c", companyDto);
            map.put("s", sysUserTokenDTO);
            map.put("v", vendorDto);
            map.put("count", count);
            map.put("sysDate",sysDate);
            map.put("purDate",purDate);
        }else{
            throw new ServiceErrorException("该订购单数据未查到");
        }

        try {
            ExcelUtils.setResponseZF(response, fileName);
            String templatePath = StringUtils.isNotBlank(purNo) ? "templates/订购单-零星订购.xls" : "templates/订购单-零星订购无数据.xls";
            ExcelPoiUtils.writeExcelList(response, map, templatePath, fileName);
        } catch (Exception e) {
            log.error("零星订购单导出失败, 错误信息: {}", e.getMessage());
        }
    }

    /**
     * 进入我的订购单:导出订购单
     * @param purNo
     * @param response
     */
    @Override
    public void exportMyPurchaseOrder(String purNo, HttpServletResponse response) {
        String fileName;
        HashMap<String, Object> map = new HashMap<>();
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        PurCompany companyDto = purMapper.findPurCompanyInfo(sysUserTokenDTO.getCompanyId());
        DateTimeFormatter sdf2 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String sysDate = LocalDateTime.now().format(sdf2);

        if(StringUtils.isNotBlank(purNo)){
            // 查询所有订购单数据
            PurchaseOrderRequest request = new PurchaseOrderRequest();
            request.setPurNo(purNo);
            request.setSysUser(sysUserTokenDTO.getUserName());
            request.setCompanyId(sysUserTokenDTO.getCompanyId());
            request.setPurType("零星");

            List<PurchaseOrderDto> list = materialClearanceMapper.getPurchaseOrderList(request);
            PurchaseOrderDto dto = list.get(0);

            // 厂商信息
            SdVendor vendorDto = backMapper.getVendorNameByNo(dto.getVendorNo(), sysUserTokenDTO.getCompanyId());
            String vendorName = vendorDto != null ? vendorDto.getVendorName() : "";

            // 文件名构建
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyMMdd");
            String date = sdf1.format(dto.getPurDate());
            fileName = "订购单_" + vendorName + date + "-" + DateUtils.dateTimeNow() + ".xlsx";

            //时间变换
            String purDate = new SimpleDateFormat("yyyy/MM/dd").format(dto.getPurDate());

            Float count = 0.0f;
            for (PurchaseOrderDto t : list) {
                String inDateString = new SimpleDateFormat("MM/dd").format(dto.getInDate());
                t.setInDateString(inDateString);
                t.setMtlColorAndName(t.getMtlColor() + "/" + t.getMtlName());
                if (!ObjectUtils.isEmpty(t.getPurQty())) {
                    count = count + t.getPurQty();
                }
            }
            //填充模板数据
            map.put("mapList", list);
            map.put("p", dto);
            map.put("c", companyDto);
            map.put("s", sysUserTokenDTO);
            map.put("v", vendorDto);
            map.put("count", count);
            map.put("sysDate",sysDate);
            map.put("purDate",purDate);
        }else{
            fileName = "订购单_" +DateUtils.dateTimeNow() + ".xlsx";
            //填充模板数据
            map.put("c", companyDto);
            map.put("s", sysUserTokenDTO);
            map.put("sysDate",sysDate);
        }
        try {
            ExcelUtils.setResponseZF(response, fileName);
            String templatePath = StringUtils.isNotBlank(purNo) ? "templates/订购单-零星订购.xls" : "templates/订购单-零星订购无数据.xls";
            ExcelPoiUtils.writeExcelList(response, map, templatePath, fileName);
        } catch (Exception e) {
            log.error("订购单导出失败, 错误信息: {}", e.getMessage());
        }
    }

    /**
     * 进入我的订购单：勾选删除
     * @param list
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deletePurchaseOrder(List<LotNoRequest6> request) {
        /*获取基础数据*/
        String companyId = UserIdThread.get().getCompanyId();

        try {
            /*删除数据*/
            //1.批量删除:材料暂收表      MP_PUR_DIS
            int count1 = disMapper.fdPurDisDeleteBatch(request,companyId);
            log.info("删除:材料暂收表      MP_PUR_DIS 成功，影响行数：{}", count1);

            //2.批量删除:材料汇总表      MP_MTL_SUM
            int count2 = sumMapper.fdPurDisDeleteBatch(request,companyId);
            log.info("删除:材料汇总表      MP_MTL_SUM 成功，影响行数：{}", count2);

            //3.批量删除：指令数据       MP_MTL_LOT
            int count3 = lotMapper.fdPurDisDeleteBatch(request,companyId);
            log.info("删除：指令数据       MP_MTL_LOT 成功，影响行数：{}", count3);

                boolean success = count1 > 0 && count2 > 0 && count3 > 0 ;
                if (success) {
                    return ResponseInfo.ok("批量退回成功");
                } else {
                    throw new ServiceErrorException("批量退回失败");
                }
        }catch (Exception e){
            log.error("退回过程中发生异常，请检查日志",e);
            throw new ServiceErrorException("批量退回请购单发生异常，请检查日志!");
        }
    }

    /**
     * 获得时间戳+自增数据
     * @param key  根据key获得自增数据
     * @param length 自增长度
     * @param timezone 想要获得的时间戳保留字段 yyMM yyyy-MM-dd HH:mm:ss
     */
    private String generatePrefix(String key,String length,String timezone) {
        //根据key获得自增数据
        RedisAtomicInteger ato = new RedisAtomicInteger(key, redisService.getConnectionFactory());
        String l = "%0" + length + "d"; //%07d
        String value = String.format(l, ato.getAndIncrement());
        redisService.setOutTime(key);
        //时间戳
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(DateTimeFormatter.ofPattern(timezone));
        return time + value;
    }
}
